package com.midian.common.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.ClientException;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.OSSException;
import com.aliyun.openservices.oss.model.GetObjectRequest;
import com.aliyun.openservices.oss.model.OSSObject;
import com.aliyun.openservices.oss.model.ObjectMetadata;

public class FUtil {
	final static Logger logger = LoggerFactory.getLogger(FUtil.class);
	/**
	 * 存放图片
	 */
	public static final String BUCKET_NAME = "mengzhu";

	private static final String ACCESS_ID = "QynziiYlYNbObtBK";
	private static final String ACCESS_KEY = "YntVSQlNli80XPWZHPxSd1XkzDfqM2";

	/**
	 * 网络类型：内网
	 */
	public static final String NET_TYPE_INTERNAL = "http://oss-cn-shenzhen-internal.aliyuncs.com";
	/**
	 * 网络类型：公网
	 */
	public static final String NET_TYPE_PUBLIC = "http://oss-cn-shenzhen.aliyuncs.com";

	private String net_type = NET_TYPE_INTERNAL;
//	private String net_type = NET_TYPE_PUBLIC;


	public static String SUCCESS = "success";

	/**
	 * 产生一个系统唯一的文件名:当前时间毫秒 + “-” + 8位随机字符串
	 * 
	 * @return
	 */
	public String generateFileName(String bucketName) {
		return bucketName + "_" + System.currentTimeMillis() + "-"
				+ StringUtil.getRandomString(8);
	}

	/**
	 * 设置网络类型，默认使用内网
	 * 
	 * @param net_type
	 */
	public void setNetType(String net_type) {
		if (net_type != null && !"".equals(net_type))
			this.net_type = net_type;
	}

	private OSSClient getOSSClient() {
		return new OSSClient(net_type, ACCESS_ID, ACCESS_KEY);

	}

	/**
	 * 上传文件
	 * 
	 * @param bucketName
	 *            桶
	 * @param fileName
	 *            文件名
	 * @param suffix
	 *            文件后缀
	 * @param input
	 *            输入流
	 * @return 状态码，成功返回success，即本类中的静态常量SUCCESS
	 */
	public String uploadFile(String bucketName, String fileName, String suffix,
			InputStream input) throws Exception{
//		try {
			ObjectMetadata objectMeta = new ObjectMetadata();
			objectMeta.setContentLength(input.available());
			// 可以在metadata中标记文件类型
			objectMeta.setContentType(EnumGetFileContentType.valueOf(
					suffix.substring(1)).toString());
			getOSSClient().putObject(bucketName, fileName, input, objectMeta);
			return SUCCESS;
//		} catch (IOException e) {
//			logger.error("[FUtil/uploadFile]" + "IOException");
//			return "IOException";
//		} catch (OSSException e) {
//			logger.error("[FUtil/uploadFile]" + "OSSException");
//			return e.getErrorCode();
//		} catch (ClientException e) {
//			logger.error("[FUtil/uploadFile]" + "ClientException");
//			return e.getErrorCode();
//		}

	}

	public InputStream downloadFile(String filename) {
		try {
			return getOSSClient().getObject(BUCKET_NAME, filename)
					.getObjectContent();

		} catch (OSSException e) {
			logger.error("[FUtil/downloadFile]" + "OSSException");
		} catch (ClientException e) {
			logger.error("[FUtil/downloadFile]" + "ClientException");
		}
		return null;

	}

	public String downloadFileToLocal(String filename, String localFileDir) {
		try {
			File file = new File(localFileDir, filename);
			getOSSClient().getObject(
					new GetObjectRequest(BUCKET_NAME, filename),
					file);
			return SUCCESS;
		} catch (OSSException e) {
			logger.error("[FUtil/downloadFile]" + "OSSException");
			return e.getErrorCode();
		} catch (ClientException e) {
			logger.error("[FUtil/downloadFile]" + "ClientException");
			return e.getErrorCode();
		}

	}

	/**
	 * 下载文件
	 * 
	 * @param bucketName
	 *            桶名
	 * @param filename
	 *            文件名
	 * @param start
	 *            起始的字节位置，必须大于或等于0
	 * @return
	 */
	public InputStream downloadFile(String filename, int start) {

		try {
			GetObjectRequest getObjectRequest = new GetObjectRequest(
					BUCKET_NAME, filename);
			if (start < 0) {
				start = 0;
			}
			getObjectRequest.setRange(start, -1);
			return getOSSClient().getObject(getObjectRequest)
					.getObjectContent();

		} catch (OSSException e) {
			logger.error("[FUtil/downloadFile]" + "OSSException");
		} catch (ClientException e) {
			logger.error("[FUtil/downloadFile]" + "ClientException");
		}
		return null;

	}

	public Object[] downloadFileWithLength(String filename) {
		try {

			GetObjectRequest getObjectRequest = new GetObjectRequest(
					BUCKET_NAME, filename);
			OSSObject ossObject = getOSSClient().getObject(getObjectRequest);
			Object[] objects = new Object[2];
			objects[0] = ossObject.getObjectContent();
			objects[1] = ossObject.getObjectMetadata().getContentLength();
			return objects;

		} catch (OSSException e) {
			logger.error("[FUtil/downloadFile]" + "OSSException");
		} catch (ClientException e) {
			logger.error("[FUtil/downloadFile]" + "ClientException");
		}
		return null;

	}

	/**
	 * 删除文件
	 * 
	 * @param bucketName
	 *            桶
	 * @param filename
	 *            文件名
	 * @return
	 */
	public String deleteFile(String filename) {
		try {
			getOSSClient().deleteObject(BUCKET_NAME, filename);
			return SUCCESS;
		} catch (OSSException e) {
			logger.error("[FUtil/deleteFile]" + "OSSException");
			return e.getErrorCode();
		} catch (ClientException e) {
			logger.error("[FUtil/deleteFile]" + "ClientException");
			return e.getErrorCode();
		}
	}

	private void mai() {

	}
}
